<template>
  <div class="app-container">
    <div class="filter-container">
      <el-card>
        <el-form ref="searchform" :inline="true" :model="searchform" class="demo-form-inline" size="small">
          <el-form-item label="姓名：">
            <el-input v-model="searchform.Keywords" clearable placeholder="姓名" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch()">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-card>
      <div class="list-btn-container">
        <el-button-group>
          <slot v-for="itemf in loadBtnFunc">
            <el-button v-if="itemf.FullName==='新增'" type="default" icon="el-icon-plus" size="small" @click="ShowEditOrViewDialog()">新增</el-button>
            <el-button v-if="itemf.FullName==='修改'" type="default" icon="el-icon-edit" size="small" @click="ShowEditOrViewDialog('edit')">修改</el-button>
            <el-button v-if="itemf.FullName=='禁用'" type="default" icon="el-icon-video-pause" size="small" @click="setEnable('0')">禁用</el-button>
            <el-button v-if="itemf.FullName=='启用'" type="default" icon="el-icon-video-play" size="small" @click="setEnable('1')">启用</el-button>
            <el-button v-if="itemf.FullName==='软删除'" type="default" icon="el-icon-delete" size="small" @click="deleteSoft('0')">软删除</el-button>
            <el-button v-if="itemf.FullName==='删除'" type="default" icon="el-icon-delete" size="small" @click="deletePhysics()">删除</el-button>
            <el-button v-if="itemf.FullName==='重置密码'" type="default" icon="el-icon-refresh-right" size="small" @click="handleResetPassword()">重置密码</el-button>
          </slot>
          <el-button type="default" icon="el-icon-refresh" size="small" @click="loadTableData()">刷新</el-button>
        </el-button-group>
      </div>
      <el-table
        ref="gridtable"
        v-loading="tableloading"
        :data="tableData"
        border
        stripe
        highlight-current-row
        style="width: 100%"
        :default-sort="{prop: 'SortCode', order: 'descending'}"
        @select="handleSelectChange"
        @select-all="handleSelectAllChange"
        @sort-change="handleSortChange"
      >
        <el-table-column
          type="selection"
          width="30"
        />
        <el-table-column
          prop="UserId"
          label="用户编号"
          sortable="custom"
          width="230"
          fixed
        />
        <el-table-column
          prop="Name"
          label="姓名"
          sortable="custom"
          width="230"
          fixed
        />
        <!-- <el-table-column
          prop="JobTitle"
          label="职称"
          sortable="custom"
          width="230"
          fixed
        /> -->
        <el-table-column
          prop="PhoneNumber"
          label="电话"
          sortable="custom"
          width="230"
          fixed
        />
        <el-table-column
          prop="LevelDes"
          label="等级"
          sortable="custom"
          width="230"
          fixed
        />
        <el-table-column
          prop="UserId"
          label="用户编码"
          sortable="custom"
          width="230"
          fixed
        />
        <el-table-column
          prop="Introduce"
          label="简介"
          sortable="custom"
          width="200"
          fixed
        />
        <el-table-column
          label="可用"
          sortable="custom"
          width="90"
          prop="EnabledMark"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.EnabledMark === true ? 'success' : 'info'"
              disable-transitions
            >{{ scope.row.EnabledMark===true?'启用':'禁用' }}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="CreatorTime"
          label="添加时间"
          width="180"
          sortable
        /> -->
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          :current-page="pagination.currentPage"
          :page-sizes="[5,10,20,50,100, 200, 300, 400]"
          :page-size="pagination.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.pageTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog ref="dialogEditForm" :title="editFormTitle+'皮肤管理师'" :visible.sync="dialogEditFormVisible" width="960px">
      <el-form ref="editFrom" :inline="true" :model="editFrom" :rules="rules" class="demo-form-inline">
        <el-tabs v-model="activeName" type="border-card">
          <el-tab-pane label="基本信息" name="first">
            <el-form-item label="绑定用户" :label-width="formLabelWidth" prop="UserId">
              <el-select
                v-model="editFrom.UserId"
                style="width:500px"
                filterable
                placeholder="请选择用户"
                :disabled="IsDisabled"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="姓名" :label-width="formLabelWidth" prop="Name">
              <el-input v-model="editFrom.Name" style="width:500px;" placeholder="请输入姓名" autocomplete="off" clearable />
            </el-form-item>
            <!-- <el-form-item label="职称" :label-width="formLabelWidth" prop="JobTitle">
              <el-input v-model="editFrom.JobTitle" style="width:500px;" placeholder="请输入职称" autocomplete="off" clearable />
            </el-form-item> -->
            <el-form-item label="等级" :label-width="formLabelWidth" prop="Type">
              <el-select v-model="editFrom.Level" clearable placeholder="请选择等级" style="width:500px;" @change="selecetTypeChange">
                <el-option
                  v-for="item in selectLevelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="电话" :label-width="formLabelWidth" prop="PhoneNumber">
              <el-input-number v-model="editFrom.PhoneNumber" style="width:500px;" placeholder="请输入职称" autocomplete="off" clearable />
            </el-form-item>

            <el-form-item label="介绍" :label-width="formLabelWidth" prop="Introduce">
              <el-input
                v-model="editFrom.Introduce"
                type="textarea"
                :rows="2"
                style="width:500px;"
                placeholder="请输入介绍"
                autocomplete="off"
                clearable
                @input="onInput()"
              />
            </el-form-item>
            <!-- <el-form-item label="详细介绍" :label-width="formLabelWidth" prop="IntroduceDetail">
              <el-input
                v-model="editFrom.IntroduceDetail"
                type="textarea"
                :rows="3"
                style="width:500px;"
                placeholder="请输入详细介绍"
                autocomplete="off"
                clearable
                @input="onInput()"
              />
            </el-form-item> -->
            <br>
            <el-form-item label="头像" :label-width="formLabelWidth" prop="HeadImage">
              <ele-upload-image
                v-model="editFrom.HeadImage"
                :file-size="5"
                :is-show-tip="false"
                :lazy="true"
                :response-fn="handleResponse"
                :action="httpFileUploadUrl"
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="详细介绍" name="one">
            <el-form-item label="" :label-width="formLabelWidth" prop="IntroduceDetail">
              <editor v-model="content" :is-clear="isClear" style="width:900px;" @change="change" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getPage, save, getDetail, del, setEnable, delSoft } from '@/api/shop/doctorservice'
import { GetAllUsersEnable } from '@/api/security/userservice'
import * as fecha from 'element-ui/lib/utils/date'
import defaultSettings from '@/settings'
import EleUploadImage from '@/components/upload/EleUploadImage'
import editor from '@/components/Editor/editor'
export default {
  components: {
    EleUploadImage,
    editor
  },
  data() {
    return {
      searchform: {
        Keywords: ''
      },
      activeName: 'first',
      IsDisabled: false,
      httpFileUploadUrl: defaultSettings.fileUploadUrl,
      filelist: [],
      dialogHeadIconVisible: false,
      dialogHeadIconImageUrl: '',
      selectLevelOptions: [{
        value: 1,
        label: '高级皮肤管理师'
      }, {
        value: 2,
        label: '院长皮肤管理师'
      }],
      selectRole: [],
      selectedOrganizeOptions: '',
      selectOrganize: [],
      selectLinkType: [],
      options: [],
      list: [],
      content: '',
      loading: false,
      loadBtnFunc: [],
      tableData: [],
      tableloading: true,
      isClear: false,
      pagination: {
        currentPage: 1,
        pagesize: 10,
        pageTotal: 0
      },
      sortableData: {
        order: '',
        sort: ''
      },
      dialogEditFormVisible: false,
      editFormTitle: '',
      editFrom: {
        Title: '',
        Name: '',
        Introduce: '',
        IntroduceDetail: '',
        HeadImage: '',
        Type: 1,
        Level: 1,
        JobTitle: '',
        DeleteMark: false,
        PhoneNumber: '',
        UserId: ''
      },
      rules: {
        Name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 16 个字符', trigger: 'blur' }
        ],
        // JobTitle: [
        //   { required: true, message: '请输入职称', trigger: 'blur' },
        //   { min: 2, max: 50, message: '长度在 2 到 16 个字符', trigger: 'blur' }
        // ],
        UserId: [
          { required: true, message: '请选择用户', trigger: 'blur' }
        ]
      },
      formLabelWidth: '80px',
      currentId: '',
      currentSelected: []
    }
  },
  created() {
    this.pagination.currentPage = 1
    this.InitDictItem()
    this.loadTableData()
    this.loadBtnFunc = JSON.parse(localStorage.getItem('yueboncurrentfuns'))
  },
  mounted() {
    GetAllUsersEnable().then(res => {
      this.options = res.ResData.map(item => {
        return { value: `${item.Id}`, label: `${item.NickName}_${item.Id}` }
      })
    })
  },
  methods: {
    InitDictItem() {
    },
    loadTableData: function() {
      this.tableloading = true
      var seachdata = {
        'CurrentPage': this.pagination.currentPage,
        'length': this.pagination.pagesize,
        'Keywords': this.searchform.Keywords,
        'Order': this.sortableData.order,
        'Sort': this.sortableData.sort
      }
      getPage(seachdata).then(res => {
        this.tableData = res.ResData.Items
        this.pagination.pageTotal = res.ResData.TotalItems
        this.tableloading = false
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.options = this.list.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    change(val) {
      console.log(val)
    },
    handleSearch: function() {
      this.pagination.currentPage = 1
      this.loadTableData()
    },
    ShowEditOrViewDialog: function(view) {
      if (view !== undefined) {
        if (this.currentSelected.length > 1 || this.currentSelected.length === 0) {
          this.$alert('请选择一条数据进行编辑/修改', '提示')
        } else {
          this.currentId = this.currentSelected[0].Id
          this.editFormTitle = '编辑'
          this.IsDisabled = true
          this.content = ''
          this.dialogEditFormVisible = true
          this.bindEditInfo()
        }
      } else {
        this.editFormTitle = '新增'
        this.currentId = ''
        this.IsDisabled = false
        this.selectedOrganizeOptions = ''
        this.dialogEditFormVisible = true
        this.filelist = []

        this.$nextTick(function() {
          this.$refs['editFrom'].resetFields()
        })
      }
    },
    bindEditInfo: function() {
      getDetail(this.currentId).then(res => {
        this.editFrom.JobTitle = res.ResData.JobTitle
        this.editFrom.Name = res.ResData.Name
        this.editFrom.Introduce = res.ResData.Introduce
        this.editFrom.IntroduceDetail = res.ResData.IntroduceDetail
        this.editFrom.Type = res.ResData.Type
        this.editFrom.DeleteMark = res.ResData.DeleteMark
        this.editFrom.PhoneNumber = res.ResData.PhoneNumber
        this.editFrom.Level = res.ResData.Level
        this.editFrom.HeadImage = res.ResData.HeadImage
        this.editFrom.UserId = res.ResData.UserId
        this.content = res.ResData.IntroduceDetail
      })
    },
    /**
     * 新增/修改保存
     */
    saveEditForm() {
      console.log(this.editFrom.RoleId)
      this.$refs['editFrom'].validate((valid) => {
        if (valid) {
          const data = {
            JobTitle: this.editFrom.JobTitle,
            Name: this.editFrom.Name,
            Introduce: this.editFrom.Introduce,
            // IntroduceDetail: this.editFrom.IntroduceDetail,
            Type: this.editFrom.Type,
            LinkType: this.editFrom.LinkType,
            PhoneNumber: this.editFrom.PhoneNumber,
            DeleteMark: this.editFrom.DeleteMark,
            Level: this.editFrom.Level,
            HeadImage: this.editFrom.HeadImage,
            UserId: this.editFrom.UserId,
            IntroduceDetail: this.content,
            'Id': this.currentId
          }

          var url = 'doctor/Insert'
          if (this.currentId !== '') {
            url = 'doctor/Update?id=' + this.currentId
          }
          save(data, url).then(res => {
            if (res.Success) {
              this.$message({
                message: '恭喜你，操作成功',
                type: 'success'
              })
              this.dialogEditFormVisible = false
              this.currentSelected = ''
              this.selectedOrganizeOptions = ''
              this.$refs['editFrom'].resetFields()
              this.loadTableData()
              this.InitDictItem()
            } else {
              this.$message({
                message: res.ErrMsg,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    setEnable: function(val) {
      if (this.currentSelected.length === 0) {
        this.$alert('请先选择要操作的数据', '提示')
        return false
      } else {
        var currentIds = ''
        this.currentSelected.forEach(element => {
          currentIds += element.Id + ','
        })
        const data = {
          ids: currentIds,
          bltag: val
        }
        setEnable(data).then(res => {
          if (res.Success) {
            this.$message({
              message: '恭喜你，操作成功',
              type: 'success'
            })
            this.currentSelected = ''
            this.loadTableData()
          } else {
            this.$message({
              message: res.ErrMsg,
              type: 'error'
            })
          }
        })
      }
    },

    deleteSoft: function(val) {
      if (this.currentSelected.length === 0) {
        this.$alert('请先选择要操作的数据', '提示')
        return false
      } else {
        var currentIds = ''
        this.currentSelected.forEach(element => {
          currentIds += element.Id + ','
        })
        const data = {
          ids: currentIds,
          bltag: val
        }
        delSoft(data).then(res => {
          if (res.Success) {
            this.$message({
              message: '恭喜你，操作成功',
              type: 'success'
            })
            this.currentSelected = ''
            this.loadTableData()
          } else {
            this.$message({
              message: res.ErrMsg,
              type: 'error'
            })
          }
        })
      }
    },
    deletePhysics: function() {
      if (this.currentSelected.length === 0) {
        this.$alert('请先选择要操作的数据', '提示')
        return false
      } else {
        var currentIds = ''
        this.currentSelected.forEach(element => {
          currentIds += element.Id + ','
        })
        const data = {
          ids: currentIds
        }
        del(data).then(res => {
          if (res.Success) {
            this.$message({
              message: '恭喜你，操作成功',
              type: 'success'
            })
            this.currentSelected = ''
            this.loadTableData()
          } else {
            this.$message({
              message: res.ErrMsg,
              type: 'error'
            })
          }
        })
      }
    },
    /**
     * 当表格的排序条件发生变化的时候会触发该事件
     */
    handleSortChange: function(column) {
      this.sortableData.sort = column.prop
      if (column.order === 'ascending') {
        this.sortableData.order = 'asc'
      } else {
        this.sortableData.order = 'desc'
      }
      this.loadTableData()
    },
    /**
     * 当用户手动勾选checkbox数据行事件
     */
    handleSelectChange: function(selection, row) {
      this.currentSelected = selection
    },
    /**
     * 当用户手动勾选全选checkbox事件
     */
    handleSelectAllChange: function(selection) {
      this.currentSelected = selection
    },
    /**
     * 选择每页显示数量
     */
    handleSizeChange(val) {
      this.pagination.pagesize = val
      this.pagination.currentPage = 1
      this.loadTableData()
    },
    /**
     * 选择当页面
     */
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadTableData()
    },
    dateformatter(row, column, cellValue, index) {
      var date = row[column.property]
      return cellValue ? fecha.format(new Date(date), 'yyyy-MM-dd') : ''
    },
    handleResponse(response, file, fileList) {
      this.editFrom.HeadImage = defaultSettings.fileUrl + response.ResData.FilePath
      return this.editFrom.HeadImage
    },
    onInput() {
      this.$forceUpdate()
    }
  }
}
</script>
